package com.honglang.common.tools;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import freemarker.ext.jsp.TaglibFactory;
import freemarker.ext.servlet.FreemarkerServlet;
import freemarker.ext.servlet.HttpRequestHashModel;
import freemarker.ext.servlet.ServletContextHashModel;
import freemarker.template.Configuration;
import freemarker.template.Template;

public class FreeMarkStaticPageFactory {
	 
	private Configuration configuration;
	
	public FreeMarkStaticPageFactory(){
		this.inti();
	}
	
	protected void inti(){
	  if(configuration == null){
		configuration = new Configuration();
		configuration.setEncoding(Locale.getDefault(), "UTF-8");
	  }
	}
	
	
	 public void createHtmlPage(Map<Object,Object> map,String templateFilePath,String staticFilePath,HttpServletRequest request ,HttpServletResponse response) {
		   ServletContext servletContext = request.getSession().getServletContext();
		   Template template;
		   try {
			    configuration.setServletContextForTemplateLoading(servletContext, "/");
		        template = configuration.getTemplate(templateFilePath);
		        template.setEncoding("UTF-8");
		        File htmlFile = new File(staticFilePath);
		        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));
		        TaglibFactory tag = new TaglibFactory(servletContext);
		        HttpRequestHashModel hrhm = new HttpRequestHashModel(request, response, template.getObjectWrapper());
		        ServletContextHashModel sth = new ServletContextHashModel(new GenericServletAdapter(servletContext),template.getObjectWrapper());
		        map.put(FreemarkerServlet.KEY_REQUEST_PRIVATE, hrhm); 
		        map.put(FreemarkerServlet.KEY_APPLICATION_PRIVATE, sth);
		        map.put(FreemarkerServlet.KEY_JSP_TAGLIBS, tag);
		        template.process(map, out);
		        out.flush();
		        out.close();
		    } catch (Exception e) {
		          e.printStackTrace();
		    }
	 }
}
